﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Web.Mvc;
using XRM.Security.WebUI.Helpers;
using XRM.Security.WebUI.Models.InfoSystem;
using db = XRM.Security.DataAccess.Models;

namespace XRM.Security.WebUI.Models.IdentityCenter
{
    public class IdentityCenterModel : BaseViewModel, IValidatableObject
    {
        public IdentityCenterModel()
        {
            InfoSystemList = new List<InfoSystemModel>();
        }

        public IdentityCenterModel(db.IdentityCenter dbEntity)
        {
            InfoSystemList = new List<InfoSystemModel>();
            
            Id = dbEntity.IdentityCenterId;
            IdentityCenterName = dbEntity.IdentityCenterName;
            Address = dbEntity.Address;
            Contact = dbEntity.Contact;

            GetFiles(dbEntity);
            if (dbEntity.IdentityCenterInfoSystems != null && dbEntity.IdentityCenterInfoSystems.Any())
            {
                foreach (db.IdentityCenterInfoSystem item in dbEntity.IdentityCenterInfoSystems)
                {
                    InfoSystemList.Add(new InfoSystemModel(item.InfoSystem));
                }
            }
        }

        public void GetInfoSystemAll(List<db.InfoSystem> listAll)
        {
            InfoSystemAllList = new List<InfoSystemModel>();

            if (listAll != null && listAll.Any())
            {
                foreach (db.InfoSystem item in listAll)
                {
                    InfoSystemAllList.Add(new InfoSystemModel(item));
                }
            }

            InfoSystemAllList.Insert(0, new InfoSystemModel() { Id = -1, InfoSystemName = "(Выберите информационную систему)", InMaintenance = true });
        }

        public void GetFiles(db.IdentityCenter dbEntity)
        {
            FileList = new List<IdentityCenterFileModel>();
            if (dbEntity.Files != null && dbEntity.Files.Any())
            {
                foreach (db.IdentityCenterCert item in dbEntity.Files)
                {
                    FileList.Add(new IdentityCenterFileModel(item));
                }
            }
        }

        [AllowHtml]
        [Display(Name = "Наименование")]
        [Required(ErrorMessage = "Поле 'Наименование' обязательное")]
        [MaxLength(100, ErrorMessage = "Максимальная длина поля 'Наименование' 100 символов")]
        public string IdentityCenterName { get; set; }

        [AllowHtml]
        [Display(Name = "Адрес")]
        [MaxLength(200, ErrorMessage = "Максимальная длина поля 'Адрес' 200 символов")]
        public string Address { get; set; }

        [AllowHtml]
        [Display(Name = "Контакты")]
        [MaxLength(500, ErrorMessage = "Максимальная длина поля 'Контакты' 500 символов")]
        public string Contact { get; set; }

        public string FileUploadUrl { get; set; }
        public bool ShowNotValidSert { get; set; }

        [Display(Name = "Сертификаты УЦ")]
        public List<IdentityCenterFileModel> FileList { get; set; }
        [Display(Name = "Информационные системы")]
        public List<InfoSystemModel> InfoSystemList { get; set; }
        public List<InfoSystemModel> InfoSystemAllList { get; set; }
        
        public static void AddCertificate(db.IdentityCenter identityCenter, X509Certificate2 certificate, string fileName)
        {
            var identityCenterCertificate = new db.IdentityCenterCert();
            identityCenterCertificate.SetProperties( certificate, fileName );
            identityCenter.Files.Add(identityCenterCertificate);
        }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (InfoSystemList.Select(x => x.InfoSystemName).Distinct().Count() != InfoSystemList.Count())
            {
                yield return new ValidationResult("Информационные системы не уникальны");
            }
        }
    }    
}